package cn.com.dcsgo.mybatis.plus.service.impl;

import cn.com.dcsgo.mybatis.plus.domain.dto.PageDTO;
import cn.com.dcsgo.mybatis.plus.domain.po.Address;
import cn.com.dcsgo.mybatis.plus.domain.po.User;
import cn.com.dcsgo.mybatis.plus.domain.query.UserQuery;
import cn.com.dcsgo.mybatis.plus.domain.vo.AddressVO;
import cn.com.dcsgo.mybatis.plus.domain.vo.UserVO;
import cn.com.dcsgo.mybatis.plus.enums.UserStatus;
import cn.com.dcsgo.mybatis.plus.mapper.UserMapper;
import cn.com.dcsgo.mybatis.plus.service.IUserService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Dcsgo
 * @since 2024-08-31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Transactional
    @Override
    public void reduceBalance(Long id, Integer money) {
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new IllegalArgumentException("用户不存在或用户状态异常");
        }
        if (user.getBalance() < money) {
            throw new IllegalArgumentException("用户余额不足");
        }
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())//乐观锁
                .update();//执行更新操作
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO getUserAndAddressesById(Long id) {
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new IllegalArgumentException("用户状态异常");
        }
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        return userVO;
    }

    @Override
    public List<UserVO> listAndAddressesByIds(List<Long> ids) {
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        List<Long> existIds = users.stream().map(User::getId).toList();
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, existIds).list();
        if (CollUtil.isEmpty(addresses)) {
            return BeanUtil.copyToList(users, UserVO.class);
        }
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        Map<Long, List<AddressVO>> addresMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        List<UserVO> userVOS = new ArrayList<>();
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(addresMap.get(user.getId()));
            userVOS.add(userVO);
        }
        return userVOS;
    }

    @Override
    public List<AddressVO> queryAddresses(Long id) {
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new IllegalArgumentException("用户状态异常");
        }
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        return BeanUtil.copyToList(addresses, AddressVO.class);
    }

    @Override
    public PageDTO<UserVO> queryUsersByPage(UserQuery query) {
        String name = query.getName();
        Integer status = query.getStatus();
        Integer minBalance = query.getMinBalance();
        Integer maxBalance = query.getMaxBalance();
        Page<User> page = query.toMpPageDefaultOrderByUpdateTime();
        lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .page(page);

        return PageDTO.of(page, user -> {
            if (user.getUsername().length() > 4) {
                user.setUsername(user.getUsername().substring(0, 4) + "...");
            }
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, user.getId()).list();
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
            return userVO;
        });
    }
}